package com.luckku.boot.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.luckku.boot.common.exception.ApiAsserts;
import com.luckku.boot.entity.Admin;
import com.luckku.boot.jwt.JwtUtil;
import com.luckku.boot.mapper.AdminMapper;
import com.luckku.boot.service.AdminService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.luckku.boot.utils.MD5Utils;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Luckku
 * @since 2022-10-09
 */
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements AdminService {

    @Override
    public Admin executeRegister(Admin admin) {
        LambdaQueryWrapper<Admin> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Admin::getAdminAccount, admin.getAdminAccount());
        Admin haveAdmin = baseMapper.selectOne(wrapper);
        if (!ObjectUtils.isEmpty(haveAdmin)) {
            ApiAsserts.fail("账号已存在！");
        }
        Admin addAdmin = Admin.builder()
                .adminAccount(admin.getAdminAccount())
                .adminPwd(MD5Utils.getPwd(admin.getAdminPwd()))
                .adminName(admin.getAdminName())
                .adminRole(admin.getAdminRole())
                .build();
        baseMapper.insert(addAdmin);

        return addAdmin;
    }

    @Override
    public Map<String, String> executeLogin(Admin admin) {
        Map<String, String> map = new HashMap<>(16);

        QueryWrapper<Admin> queryWrapper = new QueryWrapper();
        queryWrapper.lambda().eq(Admin::getAdminAccount, admin.getAdminAccount())
                .eq(Admin::getAdminPwd, MD5Utils.getPwd(admin.getAdminPwd()));
        Admin exist = baseMapper.selectOne(queryWrapper);
        if (ObjectUtils.isEmpty(exist)) {
            return map;
        }
        String token = JwtUtil.generateToken(String.valueOf(admin.getAdminAccount()));
        map.put("token", token);
        map.put("adminId",exist.getAdminId().toString());
        map.put("adminName",exist.getAdminName());
        map.put("adminAccount",exist.getAdminAccount());
        map.put("adminPwd",exist.getAdminPwd());
        map.put("adminRole",exist.getAdminRole());
        return map;
    }
}
